<?php

namespace App\Http\Requests\Logic\Department;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Http\FormRequest;

class StoreResource extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
		/**
		 * @var User $user
		 */
		$user = $this->user();
		if ($company = $user->getCompany()) {
			$this->offsetSet('company_id', $company->id);
			return true;
		}
        return false;
    }

	/**
	 * 定义表单验证规则
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @return array
	 */
    public function rules()
    {
		return [
        	'name' => [
        		'required',
				function ($attribute, $value, $fail)
				{
					$result = DB::table('departments')
						->where('company_id', $this->company_id)
						->where($attribute, $value)->count();
					if ($result > 0) {
						return $fail('您输入的部门名称已存在');
					}
				}
			]
        ];
    }

	/**
	 * 定义验证错误提示
	 *
	 * Date: 18/04/2018
	 * @author George
	 * @return array
	 */
	public function messages()
	{
		return [
			'name.required' => '请输入部门名称'
		];
    }
}
